package com.uniflow.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uniflow.entity.ApiApplication;
import com.uniflow.mapper.ApiApplicationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * API应用服务层
 * 
 * @author uniflow
 * @since 1.0.0
 */
@Service
public class ApiApplicationService {
    
    @Autowired
    private ApiApplicationMapper apiApplicationMapper;
    
    /**
     * 分页查询API应用
     */
    public IPage<ApiApplication> getApplicationPage(int pageNum, int pageSize, String appName, Integer status, String contactEmail, String keyword) {
        Page<ApiApplication> page = new Page<>(pageNum, pageSize);
        return apiApplicationMapper.selectApplicationPage(page, appName, status, contactEmail, keyword);
    }
    
    /**
     * 根据ID查询应用
     */
    public ApiApplication getApplicationById(String id) {
        return apiApplicationMapper.selectById(id);
    }
    
    /**
     * 根据应用名称查询
     */
    public ApiApplication getApplicationByName(String appName) {
        return apiApplicationMapper.selectByAppName(appName);
    }
    
    /**
     * 检查应用名称是否存在
     */
    public boolean existsByAppName(String appName, String excludeId) {
        return apiApplicationMapper.existsByAppName(appName, excludeId);
    }
    
    /**
     * 查询启用的应用列表
     */
    public List<ApiApplication> getEnabledApplications() {
        return apiApplicationMapper.selectEnabledApplications();
    }
    
    /**
     * 查询应用统计信息
     */
    public ApiApplication.ApiApplicationStats getApplicationStats(String appId) {
        return apiApplicationMapper.selectApplicationStats(appId);
    }
    
    /**
     * 创建API应用
     */
    @Transactional
    public ApiApplication createApplication(ApiApplication application) {
        // 生成ID
        application.setId(UUID.randomUUID().toString().replace("-", ""));
        
        // 设置创建时间
        application.setCreatedAt(LocalDateTime.now());
        
        // 检查应用名称是否重复
        if (apiApplicationMapper.existsByAppName(application.getAppName(), null)) {
            throw new RuntimeException("应用名称已存在");
        }
        
        // 设置默认状态
        if (application.getStatus() == null) {
            application.setStatus(1); // 默认启用
        }
        
        apiApplicationMapper.insert(application);
        return application;
    }
    
    /**
     * 更新API应用
     */
    @Transactional
    public ApiApplication updateApplication(ApiApplication application) {
        // 检查应用是否存在
        ApiApplication existingApp = apiApplicationMapper.selectById(application.getId());
        if (existingApp == null) {
            throw new RuntimeException("应用不存在");
        }
        
        // 检查应用名称是否重复
        if (apiApplicationMapper.existsByAppName(application.getAppName(), application.getId())) {
            throw new RuntimeException("应用名称已存在");
        }
        
        apiApplicationMapper.updateById(application);
        return application;
    }
    
    /**
     * 删除API应用
     */
    @Transactional
    public void deleteApplication(String id) {
        apiApplicationMapper.deleteById(id);
    }
    
    /**
     * 批量更新状态
     */
    @Transactional
    public void batchUpdateStatus(List<String> ids, Integer status) {
        apiApplicationMapper.batchUpdateStatus(ids, status);
    }
    
    /**
     * 查询应用调用统计
     */
    public List<Map<String, Object>> getCallStatistics(String appId, String startDate, String endDate) {
        return apiApplicationMapper.selectCallStatistics(appId, startDate, endDate);
    }
    
    /**
     * 查询热门应用
     */
    public List<ApiApplication> getPopularApplications(Integer limit) {
        return apiApplicationMapper.selectPopularApplications(limit);
    }
    
    /**
     * 查询应用总数
     */
    public Long getTotalCount() {
        return apiApplicationMapper.selectTotalCount();
    }
    
    /**
     * 查询启用应用数
     */
    public Long getEnabledCount() {
        return apiApplicationMapper.selectEnabledCount();
    }
    
    /**
     * 查询今日新增应用数
     */
    public Long getTodayNewCount() {
        return apiApplicationMapper.selectTodayNewCount();
    }
    
    /**
     * 查询应用分布统计
     */
    public List<Map<String, Object>> getDistributionStats() {
        return apiApplicationMapper.selectDistributionStats();
    }
    
    /**
     * 查询应用使用趋势
     */
    public List<Map<String, Object>> getUsageTrend(Integer days) {
        return apiApplicationMapper.selectUsageTrend(days);
    }
    
    /**
     * 查询应用错误率统计
     */
    public List<Map<String, Object>> getErrorRateStats() {
        return apiApplicationMapper.selectErrorRateStats();
    }
    
    /**
     * 查询应用性能统计
     */
    public List<Map<String, Object>> getPerformanceStats() {
        return apiApplicationMapper.selectPerformanceStats();
    }
    
    /**
     * 查询应用详情（包含密钥信息）
     */
    public ApiApplication getApplicationWithKeys(String id) {
        return apiApplicationMapper.selectWithKeys(id);
    }
    
    /**
     * 查询最近活跃的应用
     */
    public List<ApiApplication> getRecentActiveApplications(Integer limit) {
        return apiApplicationMapper.selectRecentActiveApplications(limit);
    }
    
    /**
     * 查询长时间未使用的应用
     */
    public List<ApiApplication> getInactiveApplications(Integer days) {
        return apiApplicationMapper.selectInactiveApplications(days);
    }
    
    /**
     * 查询高频调用应用
     */
    public List<ApiApplication> getHighFrequencyApplications(Integer limit) {
        return apiApplicationMapper.selectHighFrequencyApplications(limit);
    }
    
    /**
     * 查询应用IP访问统计
     */
    public List<Map<String, Object>> getIpAccessStats(String appId) {
        return apiApplicationMapper.selectIpAccessStats(appId);
    }
    
    /**
     * 查询应用API调用分布
     */
    public List<Map<String, Object>> getApiCallDistribution(String appId) {
        return apiApplicationMapper.selectApiCallDistribution(appId);
    }
    
    /**
     * 查询应用时段访问统计
     */
    public List<Map<String, Object>> getHourlyAccessStats(String appId) {
        return apiApplicationMapper.selectHourlyAccessStats(appId);
    }
    
    /**
     * 查询应用月度统计
     */
    public List<Map<String, Object>> getMonthlyStats(String appId, Integer months) {
        return apiApplicationMapper.selectMonthlyStats(appId, months);
    }
}